import router from "@/router";
import { useUserStore } from "@/stores";
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig } from "axios";
import { ElMessage } from "element-plus";

// 创建 axios 实例
const myRequest:AxiosInstance = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 10000
})

// 请求拦截器
myRequest.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在发送请求之前做些什么，比如添加 token
    const token = useUserStore().userInfo?.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 响应拦截器
myRequest.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status >= 200 && response.status < 300) {
      return response
    } else if (response.status === 401) {
      ElMessage.error('登录过期，请重新登录')
      router.push('/login')
      return Promise.reject(response)
    } else {
      ElMessage.error(response.data?.message)
      return Promise.reject(response)
    }
  },
  (error) => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
)

// 封装请求

interface Result<T> {
  message: string
  data: T
}
export const http = <T>(options: AxiosRequestConfig) => {
  return myRequest<Result<T>>({
    ...options,
  })
}
